package com.dmz.insclient.utils;


import lombok.extern.slf4j.Slf4j;
import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.DocumentHelper;
import org.dom4j.Element;
import org.dom4j.io.XMLWriter;

import java.io.IOException;
import java.io.StringWriter;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @author lee
 */
@Slf4j
public class XmlUtils {

    //获取节点内容放入map
    public static void readStringXml(String xml) {
        Document doc = null;
        Map map = new HashMap();
        String ret = null;
        try {

            doc = DocumentHelper.parseText(xml.trim());//将字符串转成xml
            Element rootElt = doc.getRootElement();//获取根节点
            //获取第一层节点
            List<Element> childElements = rootElt.elements();
            for (Element child : childElements) {
                //获取第二层节点
                List<Element> secondtList = child.elements();
                for (Element secondelements : secondtList) {
                    if (!(secondelements.getText().trim().equals("") || secondelements.getText().trim() == null)) {//去除空值节点
                        map.put(child.getName().toString() + "/" + secondelements.getName().toString(), secondelements.getText().toString());
                    } else {//获取第三层节点
                        List<Element> thirdList = secondelements.elements();
                        if (!thirdList.isEmpty()) {
                            for (Element thirdelements : thirdList) {
                                if (!thirdelements.getText().trim().equals("") && thirdelements.getText().trim() != null) {//去除空值节点
                                    map.put(child.getName().toString() + "/" + secondelements.getName().toString() + "/" + thirdelements.getName().toString(), thirdelements.getText().toString());
                                }
                            }
                        }
                    }
                }
            }
        } catch (DocumentException e) {
            log.error(e.getMessage(), e);
        } catch (Exception e) {
            log.error(e.getMessage(), e);
        }
        //System.out.println("map："+map);//输出map
    }


    //按照不同的交易生成不同的xml模板
    public static Document generateXmlHead(String tranType) {
        SimpleDateFormat sdfDate = new SimpleDateFormat("yyyyMMdd");
        SimpleDateFormat sdfTime = new SimpleDateFormat("HHmmss");
        Document doc = DocumentHelper.createDocument();
        Element root = doc.addElement("MsgText");
        Element head = root.addElement("GrpHdr");
        Element Version = head.addElement("Version");
        Version.setText("1.0.0");
        Element Ref = head.addElement("Ref");
        Element BusCd = head.addElement("BusCd");
        Element TradSrc = head.addElement("TradSrc");
        TradSrc.setText("B");
        Element Sender = head.addElement("Sender");
        Element InstIdSender = Sender.addElement("InstId");
        Element Recver = head.addElement("Recver");
        Element InstIdRecver = Recver.addElement("InstId");
        Element Resend = head.addElement("Resend");
        Resend.setText("N");
        Element Date = head.addElement("Date");
        Date.setText(sdfDate.format(new Date()));
        Element Time = head.addElement("Time");
        Time.setText(sdfTime.format(new Date()));
        Element Dgst = head.addElement("Dgst");
        Element RstHead = head.addElement("Rst");
        Element CodeHead = RstHead.addElement("Code");
        Element InfoHead = RstHead.addElement("Info");

        if (tranType.trim().equals("0114001")) {//5.2.1系统连通性测试（社保发起）
            BusCd.setText("0114001");
            Dgst.setText("系统连通性测试");
            Element BusiText = root.addElement("BusiText");
            Element RstBody = BusiText.addElement("Rst");
            Element CodeBody = RstBody.addElement("Code");
            Element InfoHBody = RstBody.addElement("Info");
            Element BkSeq = BusiText.addElement("BkSeq");
            Element SiSeq = BusiText.addElement("SiSeq");
        } else if (tranType.trim().equals("0114002")) {//5.2.2批量文件就绪通知（社保发起）
            BusCd.setText("0114002");
            Dgst.setText("日终文件就绪通知");
            Element BusiText = root.addElement("BusiText");
            Element RstBody = BusiText.addElement("Rst");
            Element CodeBody = RstBody.addElement("Code");
            Element InfoHBody = RstBody.addElement("Info");
            Element BkSeq = BusiText.addElement("BkSeq");
            Element SiSeq = BusiText.addElement("SiSeq");
        } else if (tranType.trim().equals("0114003")) {//5.2.3批量文件重发请求（社保发起）
            BusCd.setText("0114003");
            Element BusiText = root.addElement("BusiText");
            Element RstBody = BusiText.addElement("Rst");
            Element CodeBody = RstBody.addElement("Code");
            Element InfoHBody = RstBody.addElement("Info");
            Element BkSeq = BusiText.addElement("BkSeq");
            Element SiSeq = BusiText.addElement("SiSeq");
        } else if (tranType.trim().equals("0113005")) {//5.2.4查询社保机构账户余额（社保发起）
            BusCd.setText("0113005");
            Element BusiText = root.addElement("BusiText");
            Element RstBody = BusiText.addElement("Rst");
            Element CodeBody = RstBody.addElement("Code");
            Element InfoHBody = RstBody.addElement("Info");
            Element BkSeq = BusiText.addElement("BkSeq");
            Element SiSeq = BusiText.addElement("SiSeq");
            Element BkAcct = BusiText.addElement("BkAcct");
            Element Id = BkAcct.addElement("Id");
            Element Balance = BkAcct.addElement("Balance").addAttribute("Ccy", "CNY");
        } else if (tranType.trim().equals("0214002")) {//5.3.2批量结果文件就绪通知（银行发起）
            BusCd.setText("0214002");
            Dgst.setText("日终文件就绪通知");
            CodeHead.setText("0001");
            InfoHead.setText("待处理");
            Element BusiText = root.addElement("BusiText");
            Element BkSeq = BusiText.addElement("BkSeq");
            Element FileName = BusiText.addElement("FileName");
            Element FileMD5 = BusiText.addElement("FileMD5");
            Element FileSignMsg = BusiText.addElement("FileSignMsg");
        } else if (tranType.trim().equals("0113007")) {//5.2.5	批量结算文件处理进展查询（社保发起）
            BusCd.setText("0113007");
            Dgst.setText("批量结算文件处理进展查询");
            Element BusiText = root.addElement("BusiText");
            Element BkSeq = BusiText.addElement("BkSeq");
            Element SiSeq = BusiText.addElement("SiSeq");
            Element RstBody = BusiText.addElement("Rst");
            Element CodeBody = RstBody.addElement("Code");
            Element InfoHBody = RstBody.addElement("Info");
            Element LoopCount = BusiText.addElement("LoopCount");
            Element TotalCount = BusiText.addElement("TotalCount");
            Element Loop = BusiText.addElement("Loop");
            Element FileName = Loop.addElement("FileName");
            Element FileStatus = Loop.addElement("FileStatus");
            Element FileDetail = Loop.addElement("FileDetail");
        } else if (tranType.trim().equals("0214001")) {//5.3.1系统连通性测试（银行发起）
            BusCd.setText("0214001");
            Dgst.setText("系统连通性测试");
            Element BusiText = root.addElement("BusiText");
            Element RstBody = BusiText.addElement("Rst");
            Element CodeBody = RstBody.addElement("Code");
            Element InfoHBody = RstBody.addElement("Info");
            Element BkSeq = BusiText.addElement("BkSeq");
//			Element SiSeq=BusiText.addElement("SiSeq");
        } else if (tranType.trim().equals("0224001")) {//9.2.1　日终交易核对流水（银行发起）
            BusCd.setText("0224001");
            Dgst.setText("日终交易核对流水文件就绪通知");
            CodeHead.setText("0001");
            InfoHead.setText("待处理");
            Element BusiText = root.addElement("BusiText");
            Element BkSeq = BusiText.addElement("BkSeq");
            Element FileName = BusiText.addElement("FileName");
            Element FileMD5 = BusiText.addElement("FileMD5");
            Element FileSignMsg = BusiText.addElement("FileSignMsg");
        } else if (tranType.trim().equals("0222002")) {//9.2.3　社保机构账户收支明细就绪通知（银行发起）
            BusCd.setText("0222002");
            Dgst.setText("社保机构账户收支明细文件就绪通知");
            CodeHead.setText("0001");
            InfoHead.setText("待处理");
            Element BusiText = root.addElement("BusiText");
            Element BkSeq = BusiText.addElement("BkSeq");
            Element FileName = BusiText.addElement("FileName");
            Element FileMD5 = BusiText.addElement("FileMD5");
            Element FileSignMsg = BusiText.addElement("FileSignMsg");
        } else if (tranType.trim().equals("0222002")) {//9.2.3　社保机构账户收支明细就绪通知（银行发起）
            BusCd.setText("0222002");
            Dgst.setText("社保机构账户收支明细文件就绪通知");
            CodeHead.setText("0001");
            InfoHead.setText("待处理");
            Element BusiText = root.addElement("BusiText");
            Element BkSeq = BusiText.addElement("BkSeq");
            Element FileName = BusiText.addElement("FileName");
            Element FileMD5 = BusiText.addElement("FileMD5");
            Element FileSignMsg = BusiText.addElement("FileSignMsg");
        }
        return doc;
    }

    //将doc转换为xml报文
    public static String docToXml(Document doc) {

        org.dom4j.io.OutputFormat format = new org.dom4j.io.OutputFormat();
//		format.setEncoding("GBK");
        format.setEncoding("UTF-8");
        StringWriter writer = new StringWriter();
        XMLWriter output = new XMLWriter(writer, format);
        try {
            output.write(doc);
        } catch (IOException e) {
            log.error(e.getMessage(), e);
        }
        writer.flush();
        try {
            output.close();
        } catch (IOException e) {
            log.error(e.getMessage(), e);
        }
        return writer.toString();

    }

    public static String replaceBlank(String str) {
        String dest = "";
        dest = str.replaceAll("[\\s&&[^\r\n]]*(?:[\r\n][\\s&&[^\r\n]]*)+", "");
        return dest;
    }
}
